home *** CD-ROM | disk | FTP | other *** search
- Path: dawn.mmm.com!news
- From: kjhopps@mmm.com (Kevin J Hopps)
- Newsgroups: comp.lang.c++
- Subject: Re: How do I overload 'char*' in my class. Is it possible?
- Date: 14 Feb 1996 13:16:33 GMT
- Organization: 3M - St. Paul, MN 55144-1000 US
- Distribution: world
- Message-ID: <4fsnbh$36j@dawn.mmm.com>
- References: <4fp80t$odj@alcor.usc.edu>
- Reply-To: kjhopps@mmm.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Abu Wawda (wawda@alcor.usc.edu) wrote:
- > I wrote a string class and now I would like to overload: char*
- > (character pointer), but can't figure out how to do it. I've already
- > overloaded the +, +=, ==, =, and some operator operators, but can't
- > figure how to do this (or even if it's possible). Basically I want
- > something like:
-
- > char* operator ?? ()
-
- > so that my string class can also return char*. Please help. Thanks,
-
- You can provide a conversion operator, so that a string object is
- automatically converted:
- operator const char*() const;
-
- I added the const's so that it is illegal to modify the string
- through the pointer returned by the conversion. The conversion
- works this way:
- string s;
- char a[256];
- ...
- strcpy(a, s); // automatic conversion to const char*
- strcpy(s, a); // illegal: no conversion to char*
-
- To allow this, the string class needs to guarantee a trailing
- null character is on the data.
-
- You might also consider overloading operator[].
- --
- Kevin J. Hopps e-mail: kjhopps@mmm.com
- 3M Company phone: (612) 737-4643
- 3M Center, Bldg. 235-2D-57 fax: (612) 737-2700
- St. Paul, MN 55144-1000 Opinions are my own. I don't speak for 3M.
- But 3M speaks for me -- I did not write the following line:
-
- Opinions expressed herein are my own and may not represent those of 3M.
-